package api

import (
	. "com.mgface.disobj/common"
	"encoding/json"
	"fmt"
	log "github.com/sirupsen/logrus"
	"net"
	"os"
	"strings"
	"time"
)

//启动元数据服务注册

//心跳统一3秒发送一次
func StartDNHeartbeat(metanodeAddr, nodeAddr string) {
	//该metanodeAddr作为种子节点取元数据
	client := NewReconTCPClient(metanodeAddr)
	if client == nil {
		log.Fatal(fmt.Sprintf("元数据服务连接失败,请提供一个正确的元数据服务IP地址"))
		os.Exit(-1)
	}

	//第一次查询提供元数据服务的信息
	cmd := &Cmd{Name: "get", Key: "metaNodes", Value: ""}
	cmd.Run(client)
	var results []MetaValue
	json.Unmarshal([]byte(cmd.Value), &results)
	for _, metavale := range results {
		//当key为metaNodes，RealNodeValue值为:"nodeaddr-(master|slave)"
		data := strings.Split(metavale.RealNodeValue, "-")
		if data[1] == "master" {
			metanodeAddr = data[0]
		}
	}
	//第一次向master节点发送数据
	cmd = &Cmd{Name: "set", Key: "dataNodes", Value: nodeAddr}
	client = NewTCPClient(metanodeAddr)
	cmd.Run(client)

	for {
		//以第一次master返回的数据作为种子节点
		rss, _ := json.Marshal(results)
		fmt.Println("rss:::", string(rss))

		//查询出来的数据
		srearchdata := make([]MetaValue, 0)
		for _, metavale := range results {

			//查询提供元数据服务的信息
			cmd := &Cmd{Name: "get", Key: "metaNodes", Value: ""}
			data := strings.Split(metavale.RealNodeValue, "-")
			metanodeAddr = data[0]
			//fmt.Println("mtaddr:", metanodeAddr)
			client = NewTCPClient(metanodeAddr)
			//如果创建失败，说明该metadatanode已经响应不了
			if client == nil {
				continue
			}
			//获取元服务节点
			cmd.Run(client)
			//如果出错也跳过当前遍历的节点，直接到下一个节点
			if cmd.Error != nil {
				t, ok := cmd.Error.(*net.OpError)
				if ok {
					if t.Op == "write" {
						continue
					}
				}
			} else {
				var rss []MetaValue
				json.Unmarshal([]byte(cmd.Value), &rss)
				for _, metavale := range rss {
					//当key为metaNodes，RealNodeValue值为:"nodeaddr-(master|slave)"
					data := strings.Split(metavale.RealNodeValue, "-")
					if data[1] == "master" {
						metanodeAddr = data[0]
						//如果是master的话直接赋值给results，让其遍历最新获取的数据
						srearchdata = rss
						break
					}
				}
				//再次执行发送心跳包操作
				log.Debug("当前执行的master节点为:",metanodeAddr)
				cmd = &Cmd{Name: "set", Key: "dataNodes", Value: nodeAddr}
				client = NewTCPClient(metanodeAddr)
				if client == nil {
					continue
				}
				cmd.Run(client)

			}
		}
		//假如查询出来数据，赋值
		if len(srearchdata) > 0 {
			results = srearchdata
			time.Sleep(time.Second * 3)
		} else {
			log.Fatal(fmt.Sprintf("心跳包检测不到元服务节点,请检查并重启."))
			os.Exit(-1)
		}
	}
}
